package com.example.wxy.bbtapp.Common;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.example.wxy.bbtapp.Startup.AppSettings;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by yons on 2017/9/9.
 */

public class BitmapCompress {
    //计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static void compressPicture(String filePath, String desPath) {

        Log.d(AppSettings.DebugTag, "compressPicture");

        if(!FileHelper.fileIsExists(filePath))
            return;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        try {
            Bitmap bm = BitmapFactory.decodeFile(filePath, options); // 解码文件
            FileOutputStream fos  = new FileOutputStream(desPath);
            if (bm != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
